'use strict';
const path = require('path');
const fs = require('fs');
const del = require('del');
const compressing = require('compressing');
const Controller = require('egg').Controller;
const child_process = require('child_process');
const destDir = '/var/lib/tomcat8/webapps'
// const destDir = '/Users/jonsnow93/Downloads'

const tempDir = 'app/public/temp/';

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    await this.ctx.render('upload.html');
  }

  async uploadRP(){
    const { ctx } = this;
    const file = ctx.request.files[0];
    let httpStatus = 200;

    try {
      const fileName = file.filename.split('.zip')[0];
      const fromPath = path.join(tempDir, fileName);
      const toPath = path.join(destDir, 'ROOT');
      // 清空临时目录和目标目录
      del.sync([`${tempDir}/**`], {
        force: true
      });
      del.sync([toPath], {
        force: true
      });
      // 解压
      await compressing.zip.uncompress(
          path.join(process.cwd(), file.filepath),
          tempDir,
          {
            zipFileNameEncoding: 'gbk'
          }
      );
      // 复制
      child_process.spawn('cp', ['-r', fromPath, toPath]);
    } catch (e) {
      console.log(e);
      httpStatus = 500;
    }

    ctx.status = httpStatus;

  }


}

module.exports = HomeController;
